﻿using System;
using System.Collections.Generic;
using System.Linq;
using Silent.MDB.Common.Data;
using Silent.MDB.Common.Services;

namespace Silent.MDB.Server.Model.Repositories
{
    public class FoldersRepository : IRepository<Folder>
    {
        private readonly IDataContext m_dataContext;

        public FoldersRepository(IDataContext dataContext)
        {
            m_dataContext = dataContext;
        }

        public void Add(Folder item)
        {
            m_dataContext.Folders.Add(item);
        }
        public void Update(Folder item)
        {
            var temp = m_dataContext.Folders.FirstOrDefault(x => x.ObjectId == item.ObjectId);
            if (temp != null)
            {
                temp.Name = item.Name;
                if (temp.Location != item.Location)
                {
                    m_dataContext.Folders.Remove(temp);
                    ApplicationCore.RepositoryManagers[item.Location]
                        .GetRepository<Folder>()
                        .Add(temp);
                }
            }
        }
        public void Remove(Folder item)
        {
            var temp = m_dataContext.Folders.FirstOrDefault(x => x.ObjectId == item.ObjectId);
            if (temp != null)
            {
                m_dataContext.Folders.Remove(temp);
            }
        }
        public ICollection<Folder> Load(Folder filter)
        {
            if (filter == null)
                return m_dataContext.Folders.ToList();
            return m_dataContext.Folders.Where(x => x.ParentObjectId == filter.ObjectId).ToList();
        }
        public void Save(ICollection<Folder> data)
        {
            if (data != null)
            {
                foreach (var folder in data)
                {
                    m_dataContext.Folders.Add(folder);
                }
            }
            m_dataContext.SaveChanges();
        }
    }
}
